package com.sale.taskplugins;

import com.apache.api.api.TimeTaskService;
import com.apache.api.manager.PluginConnector;
import com.apache.api.manager.ProxyManager;
import com.apache.api.vo.ParamsVo;
import com.apache.api.vo.ResultEntity;
import com.apache.database.constant.SpringContextLoader;
import com.apache.member.common.DateUtil;
import com.apache.tools.DataMap;
import com.apache.tools.NumberUtils;
import com.apache.tools.StrUtil;
import org.apache.log4j.Logger;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 【到期发行活动结束】每天定时检查发行活动，到达发行结束日，自动结束发行
 * 根据发行状况判断发行成功或者发行失败
 *
 * @author admin
 */
public class FinishActivityTaskPluginImpl implements PluginConnector, TimeTaskService {

    private Logger log = Logger.getLogger(getClass());

    @Override
    public boolean run() {
        exeFinishActivityTask();
        return true;
    }

    @Override
    public Object execute(ParamsVo arg0) throws Exception {
        exeFinishActivityTask();
        return new ResultEntity();
    }

    @SuppressWarnings({ "rawtypes" })
    private void exeFinishActivityTask() {
        List<DataMap> dataList = getSaleInfo();
        log.info("定时任务-----》结束发行活动开始");
        if (dataList.size() > 0) {
            for (DataMap saleInfo : dataList) {
                String saleId = String.valueOf(saleInfo.get("saleId"));//发行活动ID
                String buyTotalNum = String.valueOf(saleInfo.get("buyTotalNum"));//总申购数量
                String saleRatio = (String) saleInfo.get("saleRatio");//发行成功比例
                String saleNum = (String) saleInfo.get("saleNum");//发行数量
                buyTotalNum = StrUtil.doNull(buyTotalNum, "0");
                //计算实际发售成功比例
                double realRatio = NumberUtils.divide(Double.parseDouble(buyTotalNum), Double.parseDouble(saleNum), 4) * 100;
                Map<String, Object> params = new HashMap<String, Object>();
                if (realRatio < Double.parseDouble(saleRatio)) {
                    // 未达到预设比例，更改活动状态，更改用户申购信息状态--》申购失败
                    log.info("发行saleId=" + saleId + ",未达到预设成功比例，发行失败");
                    params.put("trsBuy.w_saleId", saleId);
                    params.put("trsSale.w_saleId", saleId);
                    params.put("trsSale.saleStatus", "41");//发行失败
                    params.put("trsBuy.buyStatus", "50");//申购失败
                    params.put("modelTypes", "u_trsBuy,u_trsSale");
                    updateBuyInfo(params);
                }
                if (realRatio >= Double.parseDouble(saleRatio)) {
                    //达到发行成功比例，发行成功
                    log.info("发行saleId=" + saleId + ",达到预设成功比例，发行成功，结束发行");
                    params.put("trsSale.w_saleId", saleId);
                    params.put("trsSale.saleStatus", "40");//发行成功
                    params.put("modelTypes", "u_trsSale");
                    updateBuyInfo(params);
                }
            }
        }
        log.info("定时任务-----》结束发行活动开始");
    }

    /**
     * 综合查询：查询当日为发行截止日期的所有申购活动sale对象、每个活动申购总量等
     *
     * @return
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })
    public List<DataMap> getSaleInfo() {
        ProxyManager netProxyManager = (ProxyManager) SpringContextLoader
                .getBean("netProxyManager");
        ParamsVo params = new ParamsVo();
        params.setParams("sqlKeyId", "ByObjInfo");
        params.setKey("publicForSql");
        String now = DateUtil.getNowTimeWithOutMinutes();
        StringBuilder dyncSql = new StringBuilder(
                "select s.*,(select sum(t.num) as buy_total_num from trs_buy t where t.sale_id=s.sale_id) as buy_total_num from trs_sale s");
        dyncSql.append(" where s.sale_status='30'");
        dyncSql.append(" and s.sale_date_end='" + now + "'");
        params.setParams("dyncSql", dyncSql.toString());
        log.info("自动结束发行，查询活动信息、申购总数SQL=>" + dyncSql);
        ResultEntity dymicSqlParamResult = (ResultEntity) netProxyManager.doInvoke(params);
        List<DataMap> list = (List) dymicSqlParamResult.getEntity();
        return list;
    }

    /**
     * 修改配号表信息，更新中签状态
     *
     */
    @SuppressWarnings({ "rawtypes", "unchecked", "unused" })
    public Object updateBuyInfo(Map<String, Object> buyMap) {
        ProxyManager netProxyManager = (ProxyManager) SpringContextLoader
                .getBean("netProxyManager");
        ParamsVo params = new ParamsVo();
        params.setParams(buyMap);
        params.setParams("doCode", "dymicSql");
        params.setParams("sqlKeyId", "ByDymicSql");
        params.setParams("resultType", "processSql");
        params.setKey("publicForSql");
        ResultEntity dymicSqlParamResult = (ResultEntity) netProxyManager.doInvoke(params);
        Map result = (Map) dymicSqlParamResult.getEntity();
        return null;
    }
}
